<?php

namespace yan\tagsinput;
use yii\helpers\Json;

/**
 * Main backend application asset bundle.
 */
class TagsInput extends \yii\base\Widget
{
    public $url;
    public $id;
    public $color;
    public function run(){
        $this->registerClientScript();
    }
    protected function registerClientScript()
    {
        $js = [];
        $view = $this->getView();
        $assets = TagsInputAsset::register($view);
        if(!empty($this->url)){
            $js[] = "$('#{$this->id}').tagsInput({
                width: 'auto',
                autocomplete_url:'{$this->url}'
            });";            
        }elseif(!empty($this->color)){
            $js[] = "$('#{$this->id}').tagsInput({
                width: 'auto',
                onChange: function(elem, elem_tags)
                {
                    var languages = ['php','ruby','javascript'];
                    $('.tag', elem_tags).each(function()
                    {
                        if($(this).text().search(new RegExp('\\b(' + languages.join('|') + ')\\b')) >= 0)
                            $(this).css('background-color', 'yellow');
                    });
                }
            });";
        }else{            
            $js[] = "$('#{$this->id}').tagsInput({
                width: 'auto',
            });";
        }
        $view->registerJs(implode("\n", $js));
    }

}
